package com.wang.util;

import org.apache.commons.codec.CharEncoding;
import org.apache.commons.codec.binary.Base64;

import java.io.*;
import java.net.URLDecoder;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipUtil {

    /**
     * 压缩GZip
     *
     * @return String
     */
    public static String gZip(String input) {
        byte[] bytes = null;
        GZIPOutputStream gzip = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(bos);
            gzip.write(input.getBytes(CharEncoding.UTF_8));
            gzip.finish();
            gzip.close();
            bytes = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            return "";
        } finally {
            try {
                if (gzip != null) {
                    gzip.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (final IOException ioe) {
                return "";
            }
        }
        return Base64.encodeBase64String(bytes);
    }
    public static String gZip(byte[] input) {
        byte[] bytes = null;
        GZIPOutputStream gzip = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(bos);
            gzip.write(input);
            gzip.finish();
            gzip.close();
            bytes = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            return "";
        } finally {
            try {
                if (gzip != null) {
                    gzip.close();
                }
                if (bos != null) {
                    bos.close();
                }
            } catch (final IOException ioe) {
                return "";
            }
        }
        return Base64.encodeBase64String(bytes);
    }

    public static String gZip(String input, String charset) {
        byte[] bytes = null;
        GZIPOutputStream gzip = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            gzip = new GZIPOutputStream(bos);
            gzip.write(input.getBytes(charset));
            gzip.finish();
            gzip.close();
            bytes = bos.toByteArray();
            bos.close();
        } catch (Exception e) {
            return "";
        } finally {
            try {
                if (gzip != null)
                    gzip.close();
                if (bos != null)
                    bos.close();
            } catch (final IOException ioe) {
                return "";
            }
        }
        return Base64.encodeBase64String(bytes);
    }
}
